home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6638 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: type-casting in multi-inheritance
  5. Date: 12 Feb 1996 20:20:29 +1100
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4fn0ot$msd@werple.net.au>
  8. References: <DMn7Ix.G9@Virginia.EDU>
  9. NNTP-Posting-Host: werple.mira.net.au
  10.  
  11. gcl8a@Virginia.EDU (Gregory Carl Lewin) writes:
  12.  
  13. >I am a bit fuzzy about casting from pointers to derived objects
  14. >to base classes when you are using multiple inheritance.
  15. >Perhaps someone could explain the following to me.  Consider
  16. >the arrangement:
  17.  
  18. >class Base1 {};
  19. >class Base2 {};
  20. >class Derived12 : public Base1, Base2 {};
  21.  
  22. >Base1 b1;
  23. >Base2 b2;
  24. >Derived12 d12;
  25.  
  26. >void foo(void) {
  27. >Base1* pb1;
  28. >pb1=&b1;
  29. >pb1=&d12;
  30.  
  31. >Base2* pb2;
  32. >pb2=&b2;
  33. >pb2=&d12; //ERROR: Cannot convert pointer
  34. >pb2=(Base2*) &d12;  //OK: But is it ALWAYS safe?
  35.  
  36. >}
  37.  
  38. >Because Derived 12 is publicly derived from Base1 and Base2, I
  39. >would have expected the conversion of &d12 to a Base2* to be
  40. >automatic; however, the comiler balks.  The subsequent explicit
  41. >conversion works, and the program seems to act appropriately,
  42. >but using the explicit type-cast scares me.  Can someone
  43. >explain why this is and if this is the "correct" way around the
  44. >problem (alternatives being virtual inheritance with class Base
  45. >being a base for Base1 and Base2, and ???).
  46.  
  47. The problem is that Derived12 is _not_ publicly derived from Base2.
  48. You need:
  49.     class Derived12 : public Base1, public Base2 {};
  50.     
  51. David White
  52. davidw@werple.mira.net.au
  53.